package com.example.springboot.controller;

import cn.hutool.core.collection.CollUtil;
import com.example.springboot.common.Result;
import com.example.springboot.controller.request.CategoryPageRequest;
import com.example.springboot.entity.Category;
import com.example.springboot.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 查询所有
     * @return
     */
    @GetMapping("/list")
    public Result list(){
        List<Category> list = categoryService.list();
        return Result.success(list);
    }

    /**
     * 递归实现递归树
     * @return
     */

    private List<Category> createTree(Integer pid,List<Category> categories){
        List<Category> treeList = new ArrayList<>();
        for (Category category :categories){
            if (pid ==null){
                if (category.getPid() == null){
                    treeList.add(category);
                    category.setChildren(createTree(category.getId(),categories));
                }
            }else{
                if (pid.equals(category.getPid())){
                    treeList.add(category);
                    category.setChildren(createTree(category.getId(),categories));
                }
            }
            if (CollUtil.isEmpty(category.getChildren())){
                category.setChildren(null);
            }
        }
        return treeList;
    }
    @GetMapping("/tree")
    public Result tree(){
        List<Category> list = categoryService.list();

        return Result.success(createTree(null,list));
    }


    /**
     * 分页查询
     * @return
     */
    @GetMapping("/page")
    public Result page(CategoryPageRequest categoryPageRequest){
        return Result.success(categoryService.page(categoryPageRequest));
    }
    /**
     * 新增用户
     * 前端如何把数据发送给给后台：是通过HTTP的方式，通过POST请求，把JSON数据发送给后台接口，后台接口接收到数据之后，转换成JAVA的对象，然后把Java对象，存到数据库中。
     */
    @PostMapping("/save")
    public Result save(@RequestBody Category obj){
        categoryService.save(obj);
        return Result.success();
    }
    /**
     * 根据id查询
     */
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id){
        Category obj = categoryService.getById(id);
        return Result.success(obj);
    }

    /**
     * 修改数据
     */
    @PutMapping("/update")
    public Result update(@RequestBody Category obj){
        categoryService.update(obj);
        return Result.success();
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id){
        categoryService.deleteById(id);
        return Result.success();
    }

}
